package com.jiayi.weiphoto.activity;

import java.util.ArrayList;

import com.jiayi.weiphoto.R;
import com.jiayi.weiphoto.entity.ImageEntity;
import com.jiayi.weiphoto.page.FixedHeightImageView;
import com.jiayi.weiphoto.page.HorizontalListView;
import com.jiayi.weiphoto.util.DeviceTool;
import com.jiayi.weiphoto.util.SearchSyncImageLoader;
import com.jiayi.weiphoto.util.StringUtil;
import com.jiayi.weiphoto.util.ViewsUtil;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;

public class YPInfoAdapter extends BaseAdapter{
	
	ArrayList<ImageEntity> imgs;
	Context context;
	View parentView;
	SearchSyncImageLoader imageLoader;
	
	public YPInfoAdapter(Context context, ArrayList<ImageEntity> imgs, HorizontalListView parentList){
		this.context = context;
		this.imgs = imgs;
		this.parentView = parentList;
		imageLoader = SearchSyncImageLoader.getInstance();
		imageLoader.setCacheRootPath(StringUtil.genCompanyRootPath(context));
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return imgs.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return imgs.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder holder;
		if(convertView == null){
			convertView = LayoutInflater.from(context).inflate(R.layout.ypinfo_item, null);
			holder = new ViewHolder();
			holder.imgView = (FixedHeightImageView) convertView.findViewById(R.id.iv_ypinfo_item);
			convertView.setTag(holder);
		}
		holder = (ViewHolder) convertView.getTag();
		holder.imgView.setReqHeight((int) (ViewsUtil.getScreenDM((Activity)context).heightPixels * 0.6));
		holder.imgView.setTag(imgs.get(position).getBigUrl());
		if(imgs.get(position).getPic() == null){
			imageLoader.loadImage(position, imgs.get(position).getBigUrl(), new SearchSyncImageLoader.OnImageLoadListener() {
				
				@Override
				public void onImageLoad(String iconUrl, Bitmap bitmap, int pos) {
					// TODO Auto-generated method stub
					FixedHeightImageView imgView = (FixedHeightImageView) parentView.findViewWithTag(iconUrl);
					if(imgView != null){
						imgView.setImageBitmap(bitmap);
						notifyDataSetChanged();
					}
					imgs.get(pos).setPic(bitmap);
				}
				
				@Override
				public void onError(Integer t) {
					// TODO Auto-generated method stub
					
				}
			});
		}else{
			holder.imgView.setImageBitmap(imgs.get(position).getPic());
		}
		return convertView;
	}
	
	static class ViewHolder{
		FixedHeightImageView imgView;
	}

}
